# -*- coding:utf-8 -*-

from mitmproxy import ctx
import json
from pymongo import MongoClient
from datetime import datetime


class DB(object):
    def __init__(self):
        self.client = MongoClient('127.0.0.1', 27017)
        self.db = self.client["DouYin"]
        self.collection = self.db["pinglun"]
        self.collection1 = self.db["user"]
    def insertItem(self, data):
        self.collection.insert_one(data)
    def insertItem_1(self, data):
        self.collection1.insert_one(data)
    def find(self, query):
        return self.collection1.find_one(query)
#
db = DB()

# mitmdump.exe -p 8888 -s E:\Workspaces\Python\Spider\du_app\du_script.py
# 所有发出的请求数据包都会被这个方法所处理
# 所谓的处理，我们这里只是打印一下一些项；当然可以修改这些项的值直接给这些项赋值即可
def request(flow):
    # # 获取请求对象
    # request = flow.request
    # # 实例化输出类
    # info = ctx.log.info
    # # 打印请求的url
    # info(request.url)
    # # 打印请求方法
    # info(request.method)
    # # 打印host头
    # info(request.host)
    # # 打印请求端口
    # info(str(request.port))
    # # 打印所有请求头部
    # info(str(request.headers))
    # # 打印cookie头
    # info(str(request.cookies))
    pass

# 所有服务器响应的数据包都会被这个方法处理
# 所谓的处理，我们这里只是打印一下一些项
def response(flow):
    # 获取响应对象
    response = flow.response
    # # 实例化输出类
    # info = ctx.log.info
    # # 打印响应码
    # info(str(response.status_code))
    # # 打印所有头部
    # info(str(response.headers))
    # # 打印cookie头部
    # info(str(response.cookies))
    # # 打印响应报文内容
    # info(str(response.text))

    # ctx.log.info(response.text)
    try:
        if 'api/v1/app/search/ice/search/list' in flow.request.url:
            ctx.log.info("============列表=============")
            datajson = json.loads(response.text)
            dict_data = dict()
            if datajson.get('data') is not None:
                if len(datajson.get('data')) > 0:
                    dict_data['page'] = datajson['data']['page']  # 当前页号
                    dict_data['total'] = datajson['data']['total']  # 总数
                    dict_data['productList'] = datajson['data']['productList']  # 总数
                    for d in datajson['data']['productList']:
                        dict_data['logoUrl'] = d['logoUrl']  # logo图片地址
                        dict_data['price'] = d['price']  # 价格
                        dict_data['productId'] = d['productId']  # 产品ID
                        dict_data['soldNum'] = d['soldNum']  # 销量
                        dict_data['title'] = d['title']  # 销量

                    ctx.log.info(str(dict_data))

                    ctx.log.info("=======ok========")
        # 详细信息
        if 'api/v1/app/index/ice/flow/product/detail' in flow.request.url:
            ctx.log.info("============详细信息=============")
            datajson = json.loads(response.text)
            dict_data = dict()
            if datajson.get('data') is not None:
                if len(datajson.get('data')) > 0:
                    dict_data['articleNumber'] = datajson['data']['detail']['articleNumber']  # 货号
                    dict_data['color'] = datajson['data']['detail']['color']  # 配色
                    dict_data['authPrice'] = datajson['data']['detail']['authPrice']  # 发售价格
                    dict_data['sellDate'] = datajson['data']['detail']['sellDate']  # 发售日期
                    dict_data['soldNum'] = datajson['data']['detail']['soldNum']  # 销量
                    dict_data['productId'] = datajson['data']['detail']['productId']  # 产品ID
                    dict_data['title'] = datajson['data']['detail']['title']  # 产品名称
                    dict_data['price'] = datajson['data']['item']['price']  # 现价
                    # 商品评价
                    dict_data['count'] = datajson['data']['evaluate']['count']  # 评价数量
                    dict_data['rateMsg'] = datajson['data']['evaluate']['rateMsg']  # 超赞数量
                    dict_data['sizeMsg'] = datajson['data']['evaluate']['sizeMsg']  # 尺码感受
                    if datajson.get('data').get('evaluate').get('sizes') is not None:
                        # 尺码感受列表
                        i = 0
                        for t in datajson['data']['evaluate']['sizes']:
                            dict_data['key_' + str(i)] = t['key']
                            dict_data['name_' + str(i)] = t['name']
                            dict_data['value_' + str(i)] = t['value']
                            i = i + 1

                    ctx.log.info(str(dict_data))

                    ctx.log.info("=======ok========")
        # 穿搭精选
        if 'product/relationTrends' in flow.request.url:
            ctx.log.info("============穿搭精选=============")
            datajson = json.loads(response.text)
            dict_data = dict()
            if datajson.get('data') is not None:
                if len(datajson.get('data')) > 0:
                    dict_data['total'] = datajson['data']['total']  # 总数
                    for d in datajson['data']['list']:
                        dict_data['content'] = d['trends']['content']  # 评论内容

                    ctx.log.info(str(dict_data))

                    ctx.log.info("=======ok========")

        #  最近购买
        if 'api/v1/app/product/ice/lastSoldList' in flow.request.url:
            ctx.log.info("============最近购买=============")
            datajson = json.loads(response.text)
            dict_data = dict()
            if datajson.get('data') is not None:
                dict_data['lastId'] = datajson['data']['lastId']  # 商品ID
                for d in datajson['data']['list']:
                    dict_data['formatTime'] = d['formatTime']  # 购买时间
                    dict_data['price'] = d['price']  # 购买时间
                    dict_data['sizeDesc'] = d['sizeDesc']  # 尺码
                    dict_data['userName'] = d['userName']  # 用户名
                    ctx.log.info(str(dict_data))

                    ctx.log.info("=======ok========")


    except Exception as ex:
        ctx.log.warn("============错误=============")
        ctx.log.error(ex)





